package jvlite.router;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jvlite.aop.ProxyExecutor;
import jvlite.core.JLiteContext;
import jvlite.ioc.BeanFactory;
import jvlite.render.DefaultRender;
import jvlite.render.IRender;
import jvlite.util.LogUtil;

public class RouterServlet extends HttpServlet {

	/**
	 * @author Administrator
	 */
	private static final long serialVersionUID = 8429566685330218491L;
	private static IRender defRender;

	public RouterServlet(){
		defRender = new DefaultRender();
	}
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		String url = request.getRequestURI();
		url = url.replace(request.getContextPath(), "");//.substring(1).substring(0, url.lastIndexOf("."));
		url = url.substring(1);
		url = url.substring(0, url.lastIndexOf("."));
		Map<String, String> m = JLiteContext.allActionMap;
		String value = m.get(url);
		if (value != null && !value.equals("")) {
			String fullClzName = value.substring(0, value.lastIndexOf("."));// 
			String methodName = value.substring(value.lastIndexOf(".") + 1);// 
			try {
				Class<?> clazz = Class.forName(fullClzName);
				Method method = clazz.getMethod(methodName,
						HttpServletRequest.class, HttpServletResponse.class);
				Object rtVal = null;
				Object[] args = new Object[] { request, response };
				if (JLiteContext.isAOP) {
					rtVal = ProxyExecutor.exec(fullClzName, method, args);
				} else {
					method.invoke(BeanFactory.getBeanMap().get(fullClzName), args);
				}
				if (rtVal != null) {
					request.getRequestDispatcher((String) rtVal).forward(
							request, response);
				} else {
					LogUtil.off("ctrl return null");
				}
			} catch (Throwable e) {
				this.noAuthForward(request, response);
				e.printStackTrace();
			}
		} else {
			noAuthForward(request, response);
		}
	}

	private void noAuthForward(HttpServletRequest request, HttpServletResponse response) {
		defRender.renderError(request, response);
	}
	
}